package scottb.cribbage.model {
import mx.collections.ArrayCollection;
import mx.events.CollectionEvent;
import mx.events.PropertyChangeEvent;

import spark.managers.PersistenceManager;

[Bindable]
public class ApplicationModel {

    private static var _instance:ApplicationModel = new ApplicationModel();
    
    private var dataStore:PersistenceManager = new PersistenceManager();
    
    public var game:Game;
    public var players:ArrayCollection;
    public var existingGames:ArrayCollection;
    public var completedGames:ArrayCollection;
    
    public function ApplicationModel() {

        if(null != _instance) {
            throw new Error("Singleton class");
        }

        if(dataStore.load()) {
            
            game = dataStore.getProperty("game") as Game;
            players = dataStore.getProperty("players") as ArrayCollection;  
            existingGames = dataStore.getProperty("existingGames") as ArrayCollection;
            completedGames = dataStore.getProperty("completedGames") as ArrayCollection;
        }
         
        if(!players)
            players = new ArrayCollection();
        
        if(!existingGames)
            existingGames = new ArrayCollection();
        
        if(!completedGames)
            completedGames = new ArrayCollection();
        
        players.addEventListener(CollectionEvent.COLLECTION_CHANGE, function(event:CollectionEvent):void {
           
            dataStore.setProperty("players", players);
            dataStore.save();
        });

        existingGames.addEventListener(CollectionEvent.COLLECTION_CHANGE, function(event:CollectionEvent):void {

            dataStore.setProperty("existingGames", existingGames);
            dataStore.save();
        });

        completedGames.addEventListener(CollectionEvent.COLLECTION_CHANGE, function(event:CollectionEvent):void {

            dataStore.setProperty("completedGames", completedGames);
            dataStore.save();
        });
    }
    
    public static function get instance():ApplicationModel {
        return _instance;
    }

    public function createNewGame(newGame:Game):void {
        game = newGame;
        
        game.addEventListener(PropertyChangeEvent.PROPERTY_CHANGE, function(event:PropertyChangeEvent):void {
           
            if(event.property == "started" && event.newValue) {
                dataStore.setProperty("game", game);
                existingGames.addItem(game);
            }
        });
    }

    public function clearPlayers():void {
        players.removeAll();
    }

    public function clearExistingGames():void {
        existingGames.removeAll();
    }

    public function clearCompletedGames():void {
        completedGames.removeAll();
    }
}
}
